package com.leetcode.problems060;


import java.util.Arrays;

/**
 * https://leetcode-cn.com/problems/permutation-sequence/
 * @Date 2021/11/20 14:34
 * @Author ghery
 * @Version V1.0
 */
public class Solution1 {


    public String getPermutation(int n, int k) {
        int[] factorials = new int[n + 1];
        factorials[0] = 1;
        for (int i = 1; i < factorials.length; i++) {
            factorials[i] = i * factorials[ n - 1];
        }
        --k;
        StringBuffer ans = new StringBuffer();
        int[] valid = new int[n + 1];
        Arrays.fill(valid, 1);
        for (int i = 1; i <= n; ++i) {
            int order = k / factorials[n - i] + 1;
            for (int j = 1; j <= n; ++j) {
                order -= valid[j];
                if (order == 0) {
                    ans.append(j);
                    valid[j] = 0;
                    break;
                }
            }
            k %= factorials[n - i];
        }
        return ans.toString();
    }



    public static void main(String[] args) {
        System.out.println(new Solution1().getPermutation(3,1));
    }
}
